package com.yupi.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.constant.UserConstant;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.model.User;


import com.yupi.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Y1531
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-09-21 19:45:58
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    UserMapper userMapper;
    private final String SALT = "LAN";

    @Override
    public int userRegisger(String userAccount, String userPassword, String checkPassword,String planetCode) {
        //1. 校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,planetCode)) {
            throw  new BusinessException(ErrorCode.PARAM_ERROR,"有空参数");
        }
        if (userAccount.length() < 4) {
         throw new BusinessException(ErrorCode.PARAM_ERROR,"用户名过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"密码过短");
        }
        if(planetCode.length() > 5)
        {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"编号过长");
        }
        //账户不能包含特殊字符
        String validPattern = "[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"账号包含特殊字符");
        }
        //登录密码与验证密码
        if (!checkPassword.equals(userPassword)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"两次密码不一致");
        }
        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"账户重复");
        }
        //校验id不能重复
             queryWrapper = new QueryWrapper();
        queryWrapper.eq("planetCode", planetCode);
        count = this.count(queryWrapper);
        if (count > 0) {
            return -1;
        }
        //2.加密密码

        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPassword);
        user.setPlanetCode(planetCode);
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1. 校验
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户名或密码为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户长度小于4");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户密码小于8");
        }
        //账户不能包含特殊字符
        String validPattern = "[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAM_ERROR,"用户账户包含特殊字符");
        }
        //加密
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", newPassword);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            log.info("user login failed,userAccount cant match userPassword");
            throw new BusinessException(ErrorCode.PARAM_ERROR,"没查到该用户");
        }
        //用户脱敏
        User handled = getSafety(user);
        if (request != null) {
            HttpSession session = request.getSession();
            //存储的session中
            session.setAttribute(USER_LOGIN_STATE, handled);
        }

        return handled;

    }

    @Override
    public User getSafety(User user) {
        if(user == null)
        {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"用户对象为空");
        }
        User handled = new User();
        handled.setId(user.getId());
        handled.setUsername(user.getUsername());
        handled.setUserAccount(user.getUserAccount());
        handled.setAvatarUrl(user.getAvatarUrl());
        handled.setGender(user.getGender());
        handled.setPhone(user.getPhone());
        handled.setUserRole(user.getUserRole());
        handled.setEmail(user.getEmail());
        handled.setUserStatus(user.getUserStatus());
        handled.setPlanetCode(user.getPlanetCode());
        handled.setCreateTime(user.getCreateTime());
        return handled;
    }

    @Override
    public List<User> userSerach(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<User>();
        if (StringUtils.isNoneBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> list = this.list(queryWrapper);
        return list.stream().map(user -> getSafety(user)).collect(Collectors.toList());
    }

    @Override
    public boolean userDelete(int id) {
        int i = userMapper.deleteById(id);
        if (i < 0){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return true;
    }

    /**
     *
     * @param request 获取session
     * @return
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


}




